import { EditOutlined, SearchOutlined } from '@ant-design/icons'
import { useBoolean } from '@gnlab/utils/env-react'
import { Select, Input, Spin } from 'antd'
import c from 'classnames'
import { Empty } from '@/desktop/components'
import { ManageGroups } from '@/desktop/components/words/library/manage-groups'
import { useWordsList, useWordsGroups, useFilter } from '@/desktop/logics/words-library'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { Words } from '@/services/resources/words-library'

export interface FilterChildrenProps {
  wordsList: Words[]
  showGlobal: boolean
}

export function WordsLibraryFilter({
  RenderComponent,
}: {
  RenderComponent: (props: FilterChildrenProps) => JSX.Element
}) {
  const [isAdmin] = useStreams(services.auth.isAdmin$)

  const { wordsList: allWordsList, isLoading, reload: reloadWordsList } = useWordsList()
  const { groups: allWordsGroups, reload: reloadWordsGroups } = useWordsGroups()
  const reload = useCallback(() => {
    reloadWordsList()
    reloadWordsGroups()
  }, [reloadWordsList, reloadWordsGroups])

  const {
    showGlobal,
    setShowGlobal,
    filterGroupId,
    setFilterGroupId: realSetFilterGroupId,
    filterKeyword,
    setFilterKeyword,
    groups,
    wordsList,
  } = useFilter(allWordsList, allWordsGroups, reload)

  function setFilterGroupId(id: number | '' | 'all' | 'manage') {
    if (id === 'manage') {
      manageGroups()
      realSetFilterGroupId('')
    } else {
      realSetFilterGroupId(id)
    }
  }
  const groupOptions = [
    ...(isAdmin === true ? [{ value: 'manage', label: manageGroupLabel() }] : []),
    { value: 'all', label: '全部分组' },
    { value: '', label: '未分组' },
    ...groups.map(group => ({ value: group.id, label: group.name, search: group.name })),
  ]
  const [managingGroups, manageGroups, finishManageGroups] = useBoolean(false)

  return <>
    <header>
      <div css={s.scope}>
        <div onClick={() => setShowGlobal(false)} className={c(!showGlobal && 'current')}>
          我的话术库
        </div>
        <div onClick={() => setShowGlobal(true)} className={c(showGlobal && 'current')}>
          全员话术库
        </div>
      </div>

      <div css={s.filter}>
        <Select
          popupMatchSelectWidth={false}
          showSearch
          optionFilterProp="search"
          options={groupOptions}
          value={filterGroupId}
          onChange={setFilterGroupId}
          disabled={!!filterKeyword}
        />
        <Input
          suffix={<SearchOutlined />}
          placeholder="搜索话术（全局）"
          value={filterKeyword}
          onInput={e => setFilterKeyword((e.target as HTMLInputElement).value)}
        />
      </div>
    </header>

    {isLoading ? (
      <Spin tip="加载中..." spinning>
        <div css={s.loading}></div>
      </Spin>
    ) : null}

    {!isLoading && !wordsList.length ? <Empty css={s.empty} description="没有匹配的话术" /> : null}

    {!isLoading ? <RenderComponent {...{ wordsList, showGlobal }} /> : null}

    <ManageGroups isGlobal={showGlobal} open={managingGroups} onFinish={finishManageGroups} />
  </>
}

function manageGroupLabel() {
  return <div css={s.manageGroup}>
    <EditOutlined />
    <span>管理分组</span>
  </div>
}

const s = {
  scope: css`
    align-items: center;
    display: flex;
    justify-content: center;
    padding: 12px 0;

    & > div {
      border: 1px solid #ddd;
      color: #aaa;
      cursor: pointer;
      font-size: 12px;
      padding: 3px 8px;
      &:first-of-type {
        border-radius: 8px 0 0 8px;
        border-right: none;
      }
      &:last-child {
        border-radius: 0 8px 8px 0;
      }
      &:hover {
        background-color: #fafafa;
      }
      &.current {
        background-color: #999;
        border-color: #999;
        color: #fff;
      }
    }
  `,

  filter: css`
    background-color: #f0f0f0;
    display: flex;
    flex-direction: row;
    padding: 6px 12px;

    .ant-select {
      margin-right: 8px;
      width: 100px;
    }
  `,

  manageGroup: css`
    align-items: center;
    column-gap: 4px;
    display: flex;
    color: #ffa940;
    .anticon {
      font-size: 16px;
    }
  `,

  loading: css`
    height: 200px;
  `,
  empty: css`
    margin-top: 100px;
  `,
}
